package com.niit.repository;

import com.niit.entity.Info;
import com.niit.entity.User;
import jakarta.persistence.criteria.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;

public interface UserRepository extends JpaRepository<User, Integer>, JpaSpecificationExecutor<User> {
    User findUserByInfo_IdAndUserType(Integer id, Boolean type);

    class UserSpecifications {
        public static Specification<User> withDynamicQuery(
                String phone, String username, String realName, String gender, Boolean userType) {

            return (Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
                Predicate predicate = cb.conjunction();
                Join<User, Info> infoJoin = root.join("info", JoinType.INNER);

                if (phone != null) predicate = cb.and(predicate, cb.equal(infoJoin.get("phone"), phone));
                if (username != null) predicate = cb.and(predicate, cb.equal(infoJoin.get("username"), username));
                if (realName != null) predicate = cb.and(predicate, cb.equal(infoJoin.get("realName"), realName));
                if (gender != null) predicate = cb.and(predicate, cb.equal(infoJoin.get("gender"), gender));
                if (userType != null) predicate = cb.and(predicate, cb.equal(root.get("userType"), userType));
                return predicate;
            };
        }
    }
}
